package com.cskaoyan.wordmemorize.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.cskaoyan.wordmemorize.auth.SaAdminCheckPermission;
import com.cskaoyan.wordmemorize.auth.StpKit;
import com.cskaoyan.wordmemorize.common.result.Result;
import com.cskaoyan.wordmemorize.dto.admin.*;
import com.cskaoyan.wordmemorize.listener.VocSingleExcelValidListener;
import com.cskaoyan.wordmemorize.request.BatchDeleteCommand;
import com.cskaoyan.wordmemorize.request.VocCommand;
import com.cskaoyan.wordmemorize.request.VocPageRequest;
import com.cskaoyan.wordmemorize.service.FileUploadService;
import com.cskaoyan.wordmemorize.service.VocService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.models.security.SecurityScheme;
import jakarta.annotation.Resource;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Tag(name = "后台管理-物料管理-单词管理相关接口")
@RestController
@RequestMapping("admin/voc")
public class AdminVocController {

    @Resource
    VocService vocService;


    @Operation(summary = "****添加单词",
            description = "主要用于物料管理-单词管理",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "登出成功"

                    ),
                    @ApiResponse(responseCode = "500",
                            description = "请求失败"
                    )
            }

    )
    @PostMapping("")
    @SaAdminCheckPermission("admin:voc:add")
    public Result addVocabulary(@RequestBody VocCommand command) {
        vocService.addVoc(command);
        return Result.ok();
    }

    @PutMapping("")
    @SaAdminCheckPermission("admin:voc:update")
    public Result updateVocabulary(@RequestBody VocCommand command) {
        vocService.updateVoc(command);
        return Result.ok();
    }

    @DeleteMapping("/{vocId}")
    @SaAdminCheckPermission("admin:voc:delete")
    public Result deleteVocabulary(@PathVariable Long vocId) {
        DeleteVocOperateDTO deleteVocOperateDTO = vocService.deleteVocabulary(vocId);
        return Result.ok(deleteVocOperateDTO);
    }

    @DeleteMapping("")
    @SaAdminCheckPermission("admin:voc:batchdelete")
    public Result deleteVocabularies(@RequestBody BatchDeleteCommand command) {
        List<DeleteVocOperateDTO> deleteVocOperateDTOS = vocService.deleteVocabularies(command);
        return Result.ok(deleteVocOperateDTOS);
    }

    @DeleteMapping("example/{id}")
    @SaAdminCheckPermission("admin:voc:delete")
    public Result deleteExample(@PathVariable Long id) {
        DeleteVocExampleOperateDTO deleteVocExampleOperateDTO = vocService.deleteExample(id);
        return Result.ok(deleteVocExampleOperateDTO);
    }

    @DeleteMapping("/interpretation/{id}")
    @SaAdminCheckPermission("admin:voc:delete")
    public Result deleteInterpretation(@PathVariable Long id) {
        DeleteInterpretationOperateDTO deleteInterpretationOperateDTO = vocService.deleteInterpretation(id);
        return Result.ok(deleteInterpretationOperateDTO);
    }


    @DeleteMapping("/relation/{id}")
    @SaAdminCheckPermission("admin:voc:delete")
    public Result deleteVocRelation(@PathVariable Long id) {
        DeleteVocRelationOperateDTO deleteVocRelationOperateDTO = vocService.deleteVocRelation(id);
        return Result.ok(deleteVocRelationOperateDTO);
    }

    @GetMapping("/list")
    @SaAdminCheckPermission("admin:voc:search")
    public Result getVocabularies(@ModelAttribute VocPageRequest vocPageRequest) {
        PageDTO<VocDTO> vocDTOs = vocService.getVocabularies(vocPageRequest);
        return Result.ok(vocDTOs);
    }

    @GetMapping("/template")
    public ResponseEntity<byte[]> downloadTemplate() throws IOException {
        ClassPathResource resource = new ClassPathResource("templates/单词上传模版.xlsx");
        if (!resource.exists()) {
            return ResponseEntity.notFound().build();
        }
        InputStream inputStream = resource.getInputStream();
        byte[] bytes = IOUtils.toByteArray(inputStream);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(resource.getFilename(), "UTF-8"));
        return ResponseEntity.ok().headers(headers).body(bytes);
    }

    @GetMapping("relations/{vocId}")
    @SaAdminCheckPermission("admin:voc:search")
    public Result getVocRelations(@PathVariable Long vocId) {
        List<VocChapBookDTO> vocChapBookDTOS = vocService.getVocRelations(vocId);
        return Result.ok(vocChapBookDTOS);
    }

    @PostMapping("/file")
    // @SaAdminCheckPermission("admin:voc:add")
    public Result uploadVocabularyFile(@RequestBody MultipartFile file) throws IOException {
        String link = vocService.uploadVocabularyFile(file);
        return Result.ok(link);
    }

    @DeleteMapping("file/{type}/{id}")
    @SaAdminCheckPermission("admin:voc:delete")
    public Result deleteVocabularyFile(@PathVariable String type, @PathVariable Long id, @RequestParam String name) {
        DeleteVocFileOperateDTO deleteVocFileOperateDTO = vocService.deleteFile(id, type, name);
        return Result.ok(deleteVocFileOperateDTO);
    }

    @PostMapping("/excel/validate")
    @SaAdminCheckPermission("admin:voc:excel:upload")
    public Result validateExcel(@RequestBody MultipartFile vocExcel) throws IOException {
        vocService.vocExcelValidate(vocExcel);
        return Result.ok();
    }

    @PostMapping("/excel")
    @SaAdminCheckPermission("admin:voc:excel:upload")
    public Result addVocExcel(@RequestBody MultipartFile vocExcel) throws IOException {
        Long userId = StpKit.ADMIN.getLoginIdAsLong();
        ExcelAddOperateDTO excelAddOperateDTO = vocService.addVocExcel(vocExcel, userId);
        return Result.ok(excelAddOperateDTO);
    }

}
